package com.sikaryofficial.backend.config.handler;

import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import com.sikaryofficial.common.security.utils.SecurityUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;
import org.springframework.stereotype.Component;

import java.util.Date;
import java.util.Objects;

/**
 * @author : qinjinyuan
 * @desc :  实现通用处理器：自动生成编码
 * @date : 2024/09/23 8:32
 */
@Component
@Slf4j
public class AutoGenCodeHandler implements MetaObjectHandler {

    private static final String CREATED_TIME = "createdTime";

    private static final String CREATED_BY = "createdBy";
    private static final String UPDATED_TIME = "updatedTime";

    private static final String UPDATED_BY = "updatedBy";

    /**
     *
     * 实体属性增加注解
     * @TableField(fill = FieldFill.INSERT)
     * @JSONField(format = "yyyy-MM-dd HH:mm:ss")
     * private LocalDateTime createdTime;
     *
     *  this.strictInsertFill(metaObject, "createdTime", LocalDateTime.class, LocalDateTime.now());
     *  this.strictInsertFill(metaObject, "updatedTime", LocalDateTime.class, LocalDateTime.now());
     *
     * @param metaObject
     */
    @Override
    public void insertFill(MetaObject metaObject) {
        if(Boolean.TRUE.equals(metaObject.hasSetter(CREATED_TIME)) && Objects.isNull(metaObject.getValue(CREATED_TIME))){
            this.strictInsertFill(metaObject, CREATED_TIME, Date.class, new Date());
        }
        if(Boolean.TRUE.equals(metaObject.hasSetter(CREATED_BY)) && Objects.isNull(metaObject.getValue(CREATED_BY))){
            this.strictInsertFill(metaObject, CREATED_BY, Long.class, SecurityUtils.getUserId());
        }
    }
    @Override
    public void updateFill(MetaObject metaObject) {
        if(Boolean.TRUE.equals(metaObject.hasSetter(UPDATED_TIME)) && Objects.isNull(metaObject.getValue(UPDATED_TIME))){
            this.strictUpdateFill(metaObject, UPDATED_TIME, Date.class, new Date());
        }
        if(Boolean.TRUE.equals(metaObject.hasSetter(UPDATED_BY)) && Objects.isNull(metaObject.getValue(UPDATED_BY))){
            this.strictUpdateFill(metaObject, UPDATED_BY, Long.class, SecurityUtils.getUserId());
        }
    }
}
